import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast, Button } from 'antd-mobile';
import axios from 'axios';
import { saveUserInfo } from '../utils/auth';
import styles from './Login.module.css';
import { protocol, http, port, host, viteport } from '../utils/host';

const Login: React.FC = () => {
    const navigate = useNavigate();
    const [phoneNumber, setPhoneNumber] = useState(''); // 在学号模式下存储学号
    const [verificationCode, setVerificationCode] = useState('');
    const [isPasswordMode, setIsPasswordMode] = useState(false);
    const [password, setPassword] = useState('');
    const [agreedToPrivacy, setAgreedToPrivacy] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [isLoading, setIsLoading] = useState(false);
    const [isVerificationLoading, setIsVerificationLoading] = useState(false);
    const [showLoginOptions, setShowLoginOptions] = useState(false);

    const [msg, setMsg] = useState("");

    // 恢复 QQ 登录相关 state
    const [qqModalVisible, setQqModalVisible] = useState(false);
    const [qqQrcode, setQqQrcode] = useState('');
    const [qqQrsig, setQqQrsig] = useState('');
    const [qqPolling, setQqPolling] = useState(false);

    useEffect(() => {
        if (!qqPolling || !qqQrsig) return;
        const timer = setInterval(async () => {
            const username = localStorage.getItem('username') || '';
            const res = await fetch(`${http}${host}${port}/qq-qrcode-status?qrsig=${qqQrsig}&username=${encodeURIComponent(username)}`);
            const data = await res.json();
            if (data.status === 'success') {
                if (data.qq) localStorage.setItem('qq', data.qq);
                if (data.accessToken) localStorage.setItem('accessToken', data.accessToken);
                if (data.refreshToken) localStorage.setItem('refreshToken', data.refreshToken);
                setQqPolling(false);
                setQqModalVisible(false);
                setMsg('QQ登录成功！');
                navigate('/layout/home');
            }
            if (data.status === 'expired') {
                setMsg('二维码已失效，请重试');
                setQqPolling(false);
                setQqModalVisible(false);
            }
        }, 2000);
        return () => clearInterval(timer);
    }, [qqPolling, qqQrsig, navigate]);

    // 验证手机号格式
    const validatePhoneNumber = (phone: string) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    };

    // 验证学号格式
    const validateStudentId = (studentId: string) => {
        return studentId.length >= 8 && studentId.length <= 20;
    };

    // 获取验证码
    const handleGetVerificationCode = async () => {
        if (!validatePhoneNumber(phoneNumber)) {
            Toast.show({
                content: '请输入正确的手机号码',
                position: 'center',
            });
            return;
        }

        if (!agreedToPrivacy) {
            Toast.show({
                content: '请先同意用户隐私政策',
                position: 'center',
            });
            return;
        }

        try {
            setIsVerificationLoading(true);
            await new Promise(resolve => setTimeout(resolve, 1000));

            Toast.show({
                content: '验证码已发送',
                position: 'center',
            });

            // 开始倒计时
            setCountdown(60);
            const timer = setInterval(() => {
                setCountdown(prev => {
                    if (prev <= 1) {
                        clearInterval(timer);
                        return 0;
                    }
                    return prev - 1;
                });
            }, 1000);

        } catch (error) {
            Toast.show({
                content: '发送验证码失败，请重试',
                position: 'center',
            });
        } finally {
            setIsVerificationLoading(false);
        }
    };

    // 登录处理
    const handleLogin = async () => {
        if (isPasswordMode) {
            if (!validateStudentId(phoneNumber)) {
                Toast.show({
                    content: '请输入正确的学号',
                    position: 'center',
                });
                return;
            }
        } else {
            if (!validatePhoneNumber(phoneNumber)) {
                Toast.show({
                    content: '请输入正确的手机号码',
                    position: 'center',
                });
                return;
            }
        }

        if (isPasswordMode) {
            if (!password) {
                Toast.show({
                    content: '请输入密码',
                    position: 'center',
                });
                return;
            }
        } else {
            if (!verificationCode) {
                Toast.show({
                    content: '请输入验证码',
                    position: 'center',
                });
                return;
            }
        }

        if (!agreedToPrivacy) {
            Toast.show({
                content: '请先同意用户隐私政策',
                position: 'center',
            });
            return;
        }

        try {
            setIsLoading(true);

            if (isPasswordMode) {
                // 学号登录
                const response = await axios.post(`${http}${host}${port}/login`, {
                    studentId: phoneNumber, // 在学号模式下，phoneNumber存储的是学号
                    password: password
                });

                if (response.data.code === 200) {
                    // 保存用户信息到本地存储
                    saveUserInfo(response.data.data);

                    Toast.show({
                        content: '登录成功',
                        position: 'center',
                    });

                    // 登录成功后跳转
                    navigate('/layout/home');
                } else {
                    Toast.show({
                        content: response.data.message || '登录失败',
                        position: 'center',
                    });
                }
            } else {
                // 验证码登录（暂时模拟）
                await new Promise(resolve => setTimeout(resolve, 1500));

                Toast.show({
                    content: '验证码登录功能开发中',
                    position: 'center',
                });
            }

        } catch (error: any) {
            console.error('登录错误:', error);

            let errorMessage = '登录失败，请重试';
            if (error.code === 'ERR_NETWORK') {
                errorMessage = '网络连接失败，请检查后端服务是否启动';
            } else if (error.response?.data?.message) {
                errorMessage = error.response.data.message;
            } else if (error.response?.status === 404) {
                errorMessage = '登录接口不存在，请检查后端服务';
            } else if (error.response?.status === 500) {
                errorMessage = '服务器内部错误';
            }

            Toast.show({
                content: errorMessage,
                position: 'center',
            });
        } finally {
            setIsLoading(false);
        }
    };

    // 第三方登录处理
    const handleThirdPartyLogin = (platform: string) => {
        if (platform === '邮箱2') {
            setShowLoginOptions(true);
        } else {
            Toast.show({
                content: `${platform}登录功能开发中`,
                position: 'center',
            });
        }
    };

    // 处理特殊登录方式
    const handleSpecialLogin = (loginType: string) => {
        Toast.show({
            content: `${loginType}功能开发中`,
            position: 'center',
        });
        setShowLoginOptions(false);
    };

    const handleWechatLogin = async () => {

        let params = {
            act: "login",
            appid: "3739", //自己去官网申请
            appkey: "61318d34519cbd31e177b78f2b251d62", //自己去官网申请
            type: 'wx',
            redirect_uri: `${protocol}://127.0.0.1:${viteport}/layout/home`, //回调地址,就是你登录成功(账号或扫码)之后进入到的页面
        }


        // 清除 baseURL（或设置为其他值）
        axios.defaults.baseURL = '';
        await axios.get("/api", {
            params               //替换成你自己项目的前端路径就可以 
        }).then((res) => {
            sessionStorage.setItem('longtermToken', 'hhhhnxsm')
            // 保存 code
            window.open(res.data.url, "_self") //打开第三方登录页面
        })
    };

    return (
        <div className={styles['login-container']}>
            {/* 背景装饰元素 */}
            <div className={styles['background-decoration']} />
            <div className={styles['background-decoration-2']} />

            {/* 主要内容区域 */}
            <div className={styles['main-content']}>
                {/* 标题区域 */}
                <div className={styles['title-section']}>
                    <h1 className={styles['welcome-title']}>欢迎加入校园生活</h1>
                    <p className={styles['subtitle']}>开启你的大学时光</p>
                </div>

                {/* 表单区域 */}
                <div className={styles['form-section']}>
                    {/* 手机号/学号输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type={isPasswordMode ? "text" : "tel"}
                            className={styles['input-field']}
                            placeholder={isPasswordMode ? "请输入学号" : "输入手机号"}
                            value={phoneNumber}
                            onChange={(e) => setPhoneNumber(e.target.value)}
                            maxLength={isPasswordMode ? 20 : 11}
                        />
                    </div>

                    {/* 验证码或密码输入 */}
                    {isPasswordMode ? (
                        <div className={styles['input-group']}>
                            <input
                                type="password"
                                className={styles['input-field']}
                                placeholder="输入密码"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>
                    ) : (
                        <div className={styles['input-group']}>
                            <input
                                type="text"
                                className={styles['input-field']}
                                placeholder="输入验证码"
                                value={verificationCode}
                                onChange={(e) => setVerificationCode(e.target.value)}
                                maxLength={6}
                            />
                        </div>
                    )}

                    {/* 获取验证码按钮 */}
                    {!isPasswordMode && (
                        <button
                            className={styles['verification-button']}
                            onClick={handleGetVerificationCode}
                            disabled={countdown > 0 || isVerificationLoading}
                        >
                            {countdown > 0 ? `${countdown}s后重发` : (isVerificationLoading ? '发送中...' : '获取短信验证码')}
                        </button>
                    )}

                    {/* 隐私政策 */}
                    <div className={styles['privacy-section']}>
                        <input
                            type="checkbox"
                            className={styles['privacy-checkbox']}
                            checked={agreedToPrivacy}
                            onChange={(e) => setAgreedToPrivacy(e.target.checked)}
                        />
                        <span>我已阅读并同意</span>
                        <a href="#" className={styles['privacy-link']}>
                            《用户隐私政策》
                        </a>
                    </div>

                    {/* 登录按钮 */}
                    <button
                        className={styles['login-button']}
                        onClick={handleLogin}
                        disabled={isLoading}
                    >
                        {isLoading ? '登录中...' : '登录'}
                    </button>

                    {/* 密码登录链接 */}
                    <div className={styles['password-login']}>
                        <a
                            href="#"
                            className={styles['password-login-link']}
                            onClick={(e) => {
                                e.preventDefault();
                                setIsPasswordMode(!isPasswordMode);
                                setVerificationCode('');
                                setPassword('');
                            }}
                        >
                            {isPasswordMode ? '验证码登录' : '学号登录'}
                        </a>
                    </div>

                    {/* 注册链接 */}
                    <div className={styles['password-login']}>
                        <span style={{ color: '#666', fontSize: '14px' }}>还没有账号？</span>
                        <a
                            href="#"
                            className={styles['password-login-link']}
                            onClick={(e) => {
                                e.preventDefault();
                                navigate('/register');
                            }}
                        >
                            立即注册
                        </a>
                    </div>
                </div>

                {/* 分割线 */}
                <div className={styles['divider']}>
                    <span>其它登录方式</span>
                </div>

                {/* 第三方登录 */}
                <div className={styles['third-party-login']}>
                    <button
                        className={`${styles['social-button']} ${styles['wechat-button']}`}
                        onClick={handleWechatLogin}
                    >
                        💬
                    </button>
                    <button
                        className={`${styles['social-button']} ${styles['email-button']}`}
                        onClick={() => navigate('/emaillogin')}
                    >
                        📧
                    </button>
                    <button
                        className={`${styles['social-button']} ${styles['qq-button']}`}
                        onClick={async () => {
                            const res = await fetch(`${http}${host}${port}/qq-qrcode`);
                            const data = await res.json();
                            setQqQrcode(data.img);
                            setQqQrsig(data.qrsig);
                            setQqModalVisible(true);
                            setQqPolling(true);
                        }}
                    >
                        🐧
                    </button>
                    <button
                        className={`${styles['social-button']} ${styles['email2-button']}`}
                        onClick={() => handleThirdPartyLogin('邮箱2')}
                    >
                        ···
                    </button>
                </div>
            </div>

            {/* 登录方式选择弹出层 */}
            {showLoginOptions && (
                <div className={styles['login-options-overlay']}>
                    <div className={styles['login-options-content']}>
                        <div className={styles['login-options-header']}>
                            <span className={styles['login-options-title']}>选择其他登录方式</span>
                            <button
                                className={styles['close-options-button']}
                                onClick={() => setShowLoginOptions(false)}
                            >
                                ✕
                            </button>
                        </div>
                        <div className={styles['login-options-list']}>
                            <div
                                className={styles['login-option-item']}
                                onClick={() => handleSpecialLogin('语音登录')}
                            >
                                <div className={styles['login-option-icon']}>🎤</div>
                                <div className={styles['login-option-text']}>语音登录</div>
                                <div className={styles['login-option-arrow']}>›</div>
                            </div>
                            <div
                                className={styles['login-option-item']}
                                onClick={() => navigate('/login-gesture')}
                            >
                                <div className={styles['login-option-icon']}>🎨</div>
                                <div className={styles['login-option-text']}>图形登录</div>
                                <div className={styles['login-option-arrow']}>›</div>
                            </div>
                            <div
                                className={styles['login-option-item']}
                                onClick={() => navigate('/renlianlogin')}
                            >
                                <div className={styles['login-option-icon']}>👤</div>
                                <div className={styles['login-option-text']}>人脸登录</div>
                                <div className={styles['login-option-arrow']}>›</div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* 遮罩层 */}
            {showLoginOptions && (
                <div
                    className={styles['modal-backdrop']}
                    onClick={() => setShowLoginOptions(false)}
                />
            )}

            {qqModalVisible && (
                <div className="qq-modal-bg" style={{
                    position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
                    background: 'rgba(0,0,0,0.5)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}>
                    <div style={{
                        background: 'white', borderRadius: 12, padding: 24, textAlign: 'center', minWidth: 300
                    }}>
                        <h3 style={{ marginBottom: 16 }}>QQ扫码登录</h3>
                        <img src={qqQrcode} alt="QQ二维码" style={{ width: 200, height: 200, marginBottom: 16 }} />
                        <div style={{ marginBottom: 12, color: '#888' }}>请使用QQ手机版扫码</div>
                        <Button block onClick={() => { setQqModalVisible(false); setQqPolling(false); }}>取消</Button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Login;
